# -*- coding: utf-8 -*-
import random
import subprocess
import time
import logging
import argparse
from time import sleep

from appium import webdriver
# from appium.options.android import UiAutomator2Options
# from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logger = logging

APP = "wb"

app_package_map = {
    "wb": ("com.sina.weibo", ".VisitorMainTabActivity")
}


class weiboAppiumOperate:
    def __init__(self, **kwargs):
        self.platformVersion = kwargs.get("platformVersion")
        logger.info(f"platformVersion: {self.platformVersion}")
        self.screen_width = None
        self.screen_height = None
        self.folder_name = kwargs.get("folder_name")
        self.enable_bgm = kwargs.get("enable_bgm")
        self.images_nums = kwargs.get("images_nums")
        self.title = kwargs.get("title")
        self.text = kwargs.get("text")
        self.file = kwargs.get("file")
        self.deviceName = kwargs.get("deviceName")
        self.appium_url = kwargs.get("appium_url")
        self.platformVersion = kwargs.get("platformVersion")
        self.systemPort = kwargs.get("systemPort", "8201")  # 默认 Appium System Port
        self.adbPort = kwargs.get("adbPort", "5037")
        self.driver = None
        self.max_retries = 3
        self.failure_count = 0
        self.view_count = 0
        self.like_count = 0
        self.comment_count = 0
        self.follow_count = 0

    def run(self):
        while self.max_retries > 0:
            try:
                if self.driver:
                    self.driver.quit()
                self.connection()
                logger.info(f"设备 {self.deviceName} 连接成功")
                time.sleep(3)

                logger.info("开始执行微博发图文任务...")
                self.script()

                break
            except Exception as e:
                logger.error(f"发生异常: {e}")
                self.failure_count += 1
                self.max_retries -= 1
                if self.max_retries == 0:
                    self.normal_end()
                    raise Exception("任务失败")
        logger.info("任务结束")

    @staticmethod
    def execute_adb_command(adb_command):
        """
        执行单条 ADB 命令

        :param adb_command: 完整的 ADB 命令字符串
        :return: 命令执行结果（stdout）
        """
        try:
            logger.info(f"执行 ADB 命令: {adb_command}")
            result = subprocess.run(
                adb_command,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            logger.info(f"命令执行成功: {adb_command}")
            return result.stdout.decode('utf-8')
        except subprocess.CalledProcessError as e:
            logger.error(f"命令执行失败: {adb_command}")
            logger.error(f"错误信息: {e.stderr.decode('utf-8')}")

    def initialize_device_settings(self):
        """
        执行设备初始化所需的 ADB 命令
        """
        logger.info("开始初始化设备设置")

        commands = [
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global adb_keep_usb_enabled 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global miui_optimization 0",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global tcp_keepalive 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell dumpsys battery unplug",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server.test",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global background_process_limit 5",
            f"adb -s {self.deviceName} -P {self.adbPort} shell am set-standby-bucket io.appium.uiautomator2.server ACTIVE",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm trim-caches 500M",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server.test"
        ]

        for cmd in commands:
            try:
                self.execute_adb_command(cmd)
            except Exception as e:
                logger.error(f"执行命令失败: {cmd}")
                logger.error(f"错误详情: {e}")

    def connection(self):
        self.initialize_device_settings()
        # 构造 desired_caps 字典
        desired_caps = {
            "platformName": "Android",
            "platformVersion": self.platformVersion,
            "deviceName": self.deviceName,
            "automationName": "UiAutomator2",
            "udid": self.deviceName,
            "appPackage": app_package_map[APP][0],
            "appActivity": app_package_map[APP][1],
            "noReset": True,
            "fullReset": False,
            "systemPort": int(self.systemPort),
            "adbPort": int(self.adbPort),
            "appWaitForLaunch": True,
            "skipLogcatCapture": True,
            "disableWindowAnimation": True,
            "disableAndroidWatchers": True,
            "newCommandTimeout": 180,
            "adbExecTimeout": 30000,
            "uiautomator2ServerInstallTimeout": 60000,
            "skipDeviceInitialization": True,
        }

        # 使用 desired_caps 初始化 driver（适用于 Appium 1.x）
        self.driver = webdriver.Remote(self.appium_url, desired_caps)
        # self.driver = webdriver.Remote(self.appium_url, options=UiAutomator2Options().load_capabilities(desired_caps))
        self.screen_width, self.screen_height = self.get_window_size()

    def script(self):
        """
        主流程：执行微博图文发布的完整自动化流程
        包括：
            - 打开发布页面
            - 选择相册和图片
            - 填写标题与正文
            - 提交发布
        """
        # 准备阶段：自动跳过广告
        # 启动
        time.sleep(10)
        logger.info("开始执行【发布图文】任务")

        # 步骤 1: 打开“发布”页面（点击首页右上角的发布按钮）
        self._open_publish_page()
        time.sleep(3)

        self._choose_images()
        time.sleep(3)
        # 步骤 4: 确认已选图片并点击“下一步”
        self._confirm_selected_images()
        time.sleep(5)
        # 步骤 5: 填写标题和正文内容
        self._fill_title_and_content()
        time.sleep(4)
        # 步骤 6: 最终提交图文并等待上传完成
        self._submit_post()
        time.sleep(10)
        logger.info("【发布图文】任务完成")

        # 返回首页并退出 Appium 会话
        self.normal_end()

    def _open_publish_page(self):
        logger.info("正在打开【发布】页面")
        element = self.find_element_with_retry(
            by=AppiumBy.XPATH,
            value='//androidx.compose.ui.platform.ComposeView[@resource-id="com.coolapk.market:id/bottom_navigation2"]/android.view.View/android.view.View/android.view.View[3]',
            timeout=10
        )
        element.click()

        time.sleep(3)

        element = self.find_element_with_retry(
            by=AppiumBy.ANDROID_UIAUTOMATOR,
            value='new UiSelector().text("动态")',
            timeout=5
        )
        element.click()

        '//android.widget.LinearLayout[@resource-id="com.coolapk.market:id/relative_view"]'
    def _choose_images(self):
        logger.info("点击选择图片")
        element = self.find_element_with_retry(
            by=AppiumBy.ANDROID_UIAUTOMATOR,
            value='new UiSelector().resourceId("com.coolapk.market:id/card_view")',
            timeout=5
        )
        element.click()
        time.sleep(2)
        element = self.find_element_with_retry(
            by=AppiumBy.ANDROID_UIAUTOMATOR,
            value='//android.widget.TextView[@text="最近项目"]',
            timeout=5
        )
        element.click()

    def _choose_videos(self):
        # 已在上一步点击“图片/视频”，此时自动弹出相册列表，点击【图片和视频】，进入相册
        element = self.find_element_with_retry(
            by=AppiumBy.XPATH,
            value=f'//android.widget.TextView[@text="{self.folder_name}"]/parent::android.view.ViewGroup',
            timeout=5
        )
        element.click()

        logger.info(f"准备选择 {self.images_nums} 张图片")
        for i in range(self.images_nums):
            logger.debug(f"正在点击第 {i + 1}/{self.images_nums} 张图")
            element = self.find_element_with_retry(
                by=AppiumBy.XPATH,
                value='//android.widget.FrameLayout[@content-desc="图片"]//android.widget.TextView[@content-desc="选择"][1]',
                timeout=5
            )
            element.click()

    def _confirm_selected_images(self):
        logger.info("确认已选图片并进入下一步")
        element = self.find_element_with_retry(
            by=AppiumBy.XPATH,
            value='//android.widget.TextView[@content-desc="下一步"]',
            timeout=5
        )
        element.click()

        logger.info("继续下一步")
        next_btn = self.find_element_with_retry(
            by=AppiumBy.ID,
            value='com.sina.weibo:id/nextText',

            timeout=5
        )
        next_btn.click()

    def _fill_title_and_content(self):
        logger.debug("开始填写微博正文")
        # 微博最新版：直接定位 EditText，无需额外层级

        element = self.find_element_with_retry(AppiumBy.XPATH,
                                               '//android.widget.RelativeLayout[@resource-id="com.sina.weibo:id/element_editbox"]')
        element.click()
        time.sleep(5)
        edit_element = element.find_element(AppiumBy.XPATH,
                                            '//android.widget.EditText[@resource-id="com.sina.weibo:id/edit_view"]')
        # 替换为
        edit_element.send_keys(self.text)
        logger.info("微博正文内容已填写")

    def _submit_post(self):
        logger.info("准备提交微博")
        # 微博最新版发布按钮文案为“发送”，控件 ID 为 titleSave
        publish_button = self.find_element_with_retry(
            by=AppiumBy.XPATH,
            value='//android.widget.TextView[@content-desc="发送"]',
            timeout=5
        )
        publish_button.click()
        logger.info("微博已提交，等待发布结果")

    def swipe_to_next(self):
        # 向上滑动
        self.driver.swipe(
            self.screen_width / 2,
            self.screen_height * 0.8,
            self.screen_width / 2,
            self.screen_height * 0.2,
            200
        )

    def find_element_with_retry(self, by, value, timeout=5):
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located((by, value))
            )
            return element
        except TimeoutException:
            raise NoSuchElementException(f"找不到元素: {value}")

    def get_window_size(self):
        size = self.driver.get_window_size()
        return size['width'], size['height']

    def normal_end(self):
        logger.info("返回首页并退出")
        try:
            # 先尝试轻量回首页
            self.driver.press_keycode(3)  # HOME
            time.sleep(1)
        except WebDriverException as e:
            logger.warning(f"按 HOME 时连接已断开：{e}")

        try:
            self.driver.quit()
        except WebDriverException as e:
            logger.warning(f"退出 session 时连接已断开：{e}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-accountId', '--accountId', dest='accountId', type=str, default="000", help='target accountId')

    parser.add_argument('-j', '--job_id', dest='job_id', type=str, default=None, required=True, help='target job_id')
    parser.add_argument('-u', '--appium_url', dest='appium_url', type=str, default=None, help='target appium_url')
    parser.add_argument('-d', '--deviceName', dest='deviceName', type=str, default=None, help='target deviceName')
    parser.add_argument('-s', '--systemPort', dest='systemPort', type=str, default=None, help='target systemPort')
    parser.add_argument('-a', '--adbPort', dest='adbPort', type=str, default=None, help='target adbPort')
    parser.add_argument('-p', '--platformName', dest='platformName', type=str, default=None, help='target platformName')
    parser.add_argument('-ver', '--platformVersion', dest='platformVersion', type=str, default=None,
                        help='target platformVersion')
    parser.add_argument('-v', '--variables', dest='variables', type=str, default='{}', help='target variables')
    parser.add_argument('-folder_name', '--folder_name', default="Movies", type=str)
    parser.add_argument('-images_nums', '--images_nums', type=int, required=True)
    parser.add_argument('-text', '--text', type=str, required=True)
    parser.add_argument('-file', '--file', type=str, required=False)

    args = parser.parse_args()
    weiboAppiumOperate(**vars(args)).run()
